package com.bsj.pay.util;

import java.util.Stack;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;

import com.bsj.pay.util.date.DateTimeUtil;
import com.bsj.pay.util.http.Http;
import com.bsj.pay.util.http.HttpProxy;
import com.bsj.pay.util.http.Http.Response;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ProxyIpUtil {
	private static Logger logger = LogManager.getLogger(ProxyIpUtil.class);
	
	public static Stack<HttpProxy> getNewProxy(String url) {
		if(StringUtils.isEmpty(url)) {
			return null;
		}
		Stack<HttpProxy> stack = new Stack<HttpProxy>();
		try {
			Response res = Http.create(url).get().send().getResponse();
			if (res.getStatus() == 0 || StringUtils.isEmpty(res.getResult())) {
				return null;
			}
			logger.info("获取代理IP结果：" + res.getResult());
			JSONObject json = JSONObject.fromObject(res.getResult());
			if ((json.getInt("code") == 200) || (json.getInt("code") == 0)) {
				JSONArray array = json.getJSONArray("data");
				for (int i = 0; i < array.size(); i++) {
					JSONObject ipDate = array.getJSONObject(i);
					try {
						String proxyIp = ipDate.containsKey("ip") ? ipDate.getString("ip") : ipDate.optString("IP");
						int proxyPort = ipDate.containsKey("port") ? Integer.parseInt(ipDate.getString("port"))
								: ipDate.getInt("Port");
						long expire_time = System.currentTimeMillis() / 1000 + 300;
						if (ipDate.containsKey("expire_time")) {
							expire_time = DateTimeUtil.strDate2UnixTime(ipDate.getString("expire_time"));
						} else if (ipDate.containsKey("ExpireTime")) {
							expire_time = DateTimeUtil.strDate2UnixTime(ipDate.getString("ExpireTime"));
						}
						HttpProxy proxy = new HttpProxy(proxyIp, proxyPort);
						proxy.setExpire_time(expire_time);
						stack.push(proxy);
					} catch (Exception e) {
						return null;
					}
				}
				return stack;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
